﻿@model Gateway.Console.Models.Deployment
@{
    ViewBag.Title = "Create Deployment";
}

<h2>Create Deployment</h2>

@if (ViewBag.GraphApiAuthorizationFailure)
{
    <p>
        <strong>
            An error has occurred attempting to obtain authorization for access to Azure Active Directory.<br />
        </strong>
    </p>
    <p>Details:</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorCode</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorDescription</p>
    <br />
    <p>
        <strong>
            Before this application can apply authentication to the deployed Service Gateway, it must be authorized for access to the Azure Active Directory Graph API.<br />
            Please using the <a href="https://manage.windowsazure.com" target="_blank">Azure Management Portal</a> to enable access. <br />
            Documentation describing a step-by-step process for enabling access can be found in the <a href="http://sg.codeplex.com/wikipage?title=Console" target="_blank">Service Gateway Management User Guide</a>.
        </strong>
    </p>
}
else if (ViewBag.RdfeAuthorizationFailure)
{
    <p>
        <strong>
            An error has occurred attempting to obtain authorization for access to Microsoft Azure Management API.<br />
        </strong>
    </p>
    <p>Details:</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorCode</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorDescription</p>
    <br />
    <p>
        <strong>
            Before this application can deploy the Service Gateway to Microsoft Azure, it must be authorized for access to the Microsoft Azure Management API.<br />
            Click the link below to begin the authorizing access.
        </strong>
    </p>
    <br/>
    @Html.ActionLink("Start Authorizing Access", "Index", "Security");
}
else if (Model.NoSubscriptions)
{
    <p>
        <strong>
            To deploy a Service Gateway to Microsoft Azure you must be an administrator or co-administrator in at least one Microsoft Azure subscription.<br />
            You may signup for a free trial subscription <a href="https://account.windowsazure.com/SignUp">here</a>.
        </strong>
    </p>
}
else
{
    using (Html.BeginForm("Create", "Deployment", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Subscriptions)
            @Html.DropDownListFor(model => model.SubscriptionSelection,
                    Model.Subscriptions.Select(subscription => new SelectListItem { Value = subscription.SubscriptionId, Text = subscription.SubscriptionName }),
                    new { @class = "form-control" })

        </div>
        <div id="svcName" class="form-group">
            @Html.LabelFor(model => model.ServiceName)
            @Html.TextBoxFor(model => model.ServiceName, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.ServiceName)
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Regions)
            @Html.DropDownListFor(model => model.RegionSelection,
                    Model.Regions.Select(region => new SelectListItem() { Value = region, Text = region }),
                    new { @class = "form-control" })
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.StorageAccounts)
            @Html.DropDownListFor(model => model.SelectedStorageAccount,
                Model.StorageAccounts.Select(sa => new SelectListItem() { Value = sa.Item1, Text = sa.Item2 }),
                new { @class = "form-control" })
        </div>
        <div id="createSA" class="form-group">
            @Html.LabelFor(model => model.CreateStorageAccountName)
            @Html.TextBoxFor(model => model.CreateStorageAccountName, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CreateStorageAccountName)
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.InstanceCount)
            @Html.TextBoxFor(model => model.InstanceCount, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.InstanceCount)
        </div>
        <div class="checkbox">
            @Html.LabelFor(model => model.IsHttpsEnabled)
            @Html.CheckBoxFor(model => model.IsHttpsEnabled)
        </div>
        <div id="httpsConfig">
            <div class="form-group">
                @Html.LabelFor(model => model.Certificate)
                <div class="input-group">
                    <span class="input-group-btn">
                        <span class="btn btn-default btn-file">
                            Browse… @Html.TextBoxFor(model => model.Certificate, new { type = "file" })
                        </span>
                    </span>
                    <input class="form-control" type="text" style="width:193px">
                </div>
                @Html.ValidationMessageFor(model => model.Certificate)
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.CertificatePassword)
                @Html.TextBoxFor(model => model.CertificatePassword, new { @type = "password", @class = "form-control", autocomplete = "off" })
                @Html.ValidationMessageFor(model => model.CertificatePassword)
            </div>
        </div>
        <div class="form-actions no-color">
            <input id="create" type="submit" value="Create" class="btn btn-default">
            @Html.ActionLink("Back to List", "Index")
        </div>
        <br />
        <br />
        <div id="progressBarContainer" style="width:280px;display:none">
            <div class="progress progress-striped active">
                <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                    <span class="sr-only"></span>
                </div>
            </div>
        </div>
        <div id="deploymentStatus">

        </div>
    }
}
@section Scripts {
    @if (!ViewBag.GraphApiAuthorizationFailure && !ViewBag.RdfeAuthorizationFailure && !Model.NoSubscriptions)
    {
        <script type="text/javascript">

            $(document).ready(function () {

                $("#SubscriptionSelection").change(function () {
                    $.ajax({
                        type: "GET",
                        url: '@Url.Action("GetSubscriptionRegions")',
                        data: { selectedSubscriptionId: $("#SubscriptionSelection").val() },
                        success: function (regions) {
                            $("select[id$=RegionSelection] > option").remove();
                            $(regions).each(function (idx, region) {
                                $("select[name='RegionSelection']").append($("<option>", { value: region, html: region }));
                            });
                        }
                    });

                    $.ajax({
                        type: "GET",
                        url: '@Url.Action("GetStorageAccounts")',
                        data: { selectedSubscriptionId: $("#SubscriptionSelection").val() },
                        success: function (storageAccounts) {
                            $("select[id$=SelectedStorageAccount] > option").remove();
                            $(storageAccounts).each(function (idx, saName) {
                                $("select[name='SelectedStorageAccount']").append($("<option>", { value: saName.Item1, html: saName.Item2 }));
                            });
                            $("#SelectedStorageAccount option[value='Divider']").attr('disabled', 'disabled');
                            showStorageAccount();
                        }
                    });
                });

                $("#SelectedStorageAccount").change(function() { showStorageAccount(); });
                $("#SelectedStorageAccount option[value='Divider']").attr('disabled', 'disabled');
                showStorageAccount();

                $('#IsHttpsEnabled').change(function () { showHttpsConfig(); });
                showHttpsConfig();

                $("form").validate().settings.submitHandler = function (form) {
                    $("#create").attr('disabled', true);
                    $("#progressBarContainer").show();
                    $('#deploymentStatus').empty();
                    $('#deploymentStatus').css('color', 'black');

                    //serialize the cert and form data                    
                    var fd = new FormData();
                    var input = $('#Certificate')[0];
                    fd.append('Certificate', input.files[0]);

                    var params = $(form).serializeArray();
                    $.each(params, function (i, val) {
                        fd.append(val.name, val.value);
                    });

                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("Create")',
                        data: fd,
                        contentType: false,
                        processData: false,
                        error: function (xhr, status, error) {
                            $("#progressBar").addClass("progress-bar-danger");
                            $('#deploymentStatus').css('color', 'red');
                            $('#deploymentStatus').append(error);
                        },
                        success: function (deploymentId) {
                            setInterval(function () { displayStatus(deploymentId) }, 3000);
                        }
                    });
                };
            });

            function showStorageAccount() {
                if ($("#SelectedStorageAccount").val() == "CreateNew") {
                    $("#createSA").show();
                    $("#CreateStorageAccountName").addClass("required");
                } else {
                    $("#CreateStorageAccountName").val('');
                    $("#createSA").hide();
                    $("#CreateStorageAccountName").removeClass("required");
                }
            }

            function showHttpsConfig() {
                if ($("#IsHttpsEnabled").is(":checked")) {
                    $("#httpsConfig").show();
                    $("#Certificate").addClass("required");
                    $("#CertificatePassword").addClass("required");
                }
                else {
                    $("#httpsConfig").hide();
                    $("#Certificate").val('');
                    $("#Certificate").removeClass("required");
                    $("#CertificatePassword").val('');
                    $("#CertificatePassword").removeClass("required");
                }
            }

            function displayStatus(deploymentId) {

                $.ajax({
                    type: "GET",
                    url: '@Url.Action("GetDeploymentStatus")',
                    cache: false,
                    data: { deploymentId: deploymentId },
                    error: function (xhr, status, error) {
                        $('#deploymentStatus').css('color', 'red');
                        $('#deploymentStatus').append(error);
                    },
                    success: function (data) {
                        $('#deploymentStatus').empty();
                        $.each(data, function (idx) {
                            $('#deploymentStatus').append("<div>" + data[idx].Message + "</div>");

                            if (data[idx].Success == false) {
                                $("#progressBarContainer").hide();
                                $('#deploymentStatus').css('color', 'red');
                            }

                            if (data[idx].Message.search("Finished Deployment") >= 0) {
                                window.location.href = '@Url.Action("Index")';
                            }
                        });
                    }
                });
            }

            $(document).on('change', '.btn-file :file', function () {
                var input = $(this),                
                label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
                input.trigger('fileselect', [label]);
            });

            $(document).ready(function () {
                $('.btn-file :file').on('fileselect', function (event, label) {
                    var input = $(this).parents('.input-group').find(':text');                    
                    if (input.length) {
                        input.val(label);
                    } 
                });
            });

        </script>
    }
}

